import React, { Component } from 'react';
import { Table, DatePicker, Input, message } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import tableFilter from '../../../components/tableFilter';
import ExportBtn from '../../../components/exportBtn';
import styles from './index.less';
import { getChannelText } from '../../channelType';

const { RangePicker } = DatePicker;
const { Search } = Input;
const DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';

@connect(stores => ({
  systemManager: stores.systemManager,
  channelDictionaryModel: stores.channelDictionaryModel
}))
@tableFilter
class InterfaceLog extends Component {
  state = {
    logIds: [],
    startTime: '',
    endTime: '',
    pushChannelType: '',
    pageNum: 1,
    pageSize: 10,
    msgSourceId: '',
    orderByTime: 'desc',
    totalCount: 0,
    loading: false,
    logList: [],
    exportLoading: false
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.getData();
    dispatch({
      type: 'channelDictionaryModel/channelsTypes',
      payload: {}
    });
  }

  dateChange = (e = []) => {
    this.setState(
      {
        startTime: e.length ? e[0].startOf('day').format(DATETIME_FORMAT) : undefined,
        endTime: e.length ? e[1].endOf('day').format(DATETIME_FORMAT) : undefined,
        pageNum: 1
      },
      () => {
        this.getData();
      }
    );
  };

  handleTableChange = (e, { pushChannelType }, sorter) => {
    const { current, pageSize } = e;
    this.setState(
      {
        pageNum: current,
        pageSize,
        orderByTime: sorter.order && sorter.order === 'ascend' ? 'asc' : 'desc',
        pushChannelType: (pushChannelType && pushChannelType[0]) || ''
      },
      () => {
        this.getData();
      }
    );
  };

  msgSourceIdSearch = e => {
    this.setState(
      {
        msgSourceId: e,
        pageNum: 1
      },
      () => {
        this.getData();
      }
    );
  };

  clearMsgSourceId = e => {
    if (e.target.value !== '') return;
    this.setState(
      {
        msgSourceId: '',
        pageNum: 1
      },
      () => {
        this.getData();
      }
    );
  };

  // 获取展示数据、查询、过滤、排序

  getData = () => {
    const {
      startTime,
      endTime,
      msgSourceId,
      pushChannelType,
      orderByTime,
      pageNum,
      pageSize
    } = this.state;
    const { dispatch } = this.props;
    this.setState({
      loading: true
    });
    const params = {
      startTime,
      endTime,
      msgSourceId,
      pushChannelType,
      orderByTime,
      pageNum,
      pageSize
    };

    dispatch({
      type: 'systemManager/interFaceList',
      payload: { ...params }
    }).then((res = {}) => {
      if (res.success) {
        const { datas = [], totalCount = 0 } = res;
        this.setState({
          loading: false,
          logList: datas,
          totalCount
        });
      }
    });
  };

  // 导出excel
  exportExcel = type => {
    const { dispatch } = this.props;
    const { logIds, logList } = this.state;
    if (logList.length <= 0) {
      message.error('当前没有导出内容', 1);
      return;
    }
    if (type !== 'all' && logIds.length <= 0) {
      message.error('请选择需要导出的内容', 1);
      return;
    }
    this.setState({
      exportLoading: true
    });
    const payload = {
      logIds: type === 'all' ? [] : logIds,
      pageNum: 1,
      pageSize: 10000
    };

    dispatch({
      type: 'systemManager/exportInterFaceLog',
      payload
    }).then(() => {
      this.setState({
        exportLoading: false
      });
    });
  };

  renderType = text => {
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    return <span>{getChannelText(channelsTypesData, text)}</span>;
  };

  handleDisabledDate = current => current < moment().subtract(6, 'months');

  render() {
    const { loading, pageNum, totalCount, logList, exportLoading } = this.state;
    const rowSelection = {
      onChange: selectedRowKeys => {
        this.setState({
          logIds: selectedRowKeys
        });
      }
    };
    const { channelDictionaryModel } = this.props;
    const { CHANNEL_VALUE = [] } = channelDictionaryModel;
    const columns = [
      {
        title: '调用时间',
        dataIndex: 'operateTime',
        sorter: true,
        defaultSortOrder: 'descend',
        render: text =>
          text ? moment(text).format(DATETIME_FORMAT) : '---'
      },
      {
        title: '推送目标',
        dataIndex: 'operater',
        width: 150
      },
      {
        title: '消息源ID',
        dataIndex: 'msgSourceId',
        ellipsis: true
      },
      {
        title: '渠道类型',
        dataIndex: 'pushChannelType',
        render: text => (text ? this.renderType(text) : '--'),
        filterMultiple: false,
        filters: CHANNEL_VALUE
      },
      {
        title: '渠道名称',
        dataIndex: 'pushChannelName'
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>接口日志</div>
        <div style={{ padding: '24px' }}>
          <div className={styles.topSearch}>
            <ExportBtn
              exportExcel={type => this.exportExcel(type)}
              loading={exportLoading}
            />
            <span style={{marginLeft:'16px'}}>调用时间：</span>
            <RangePicker
              style={{ width: 224, marginRight: 21 }}
              onChange={this.dateChange}
              disabledDate={this.handleDisabledDate}
            />
            <Search
              placeholder='消息源ID'
              style={{ width: 272, marginRight: 21 }}
              onSearch={this.msgSourceIdSearch}
              allowClear
              onChange={this.clearMsgSourceId}
            />
          </div>
          <Table
            style={{ background: '#fff' }}
            locale={{ emptyText: '暂无数据！' }}
            rowKey='logId'
            columns={columns}
            dataSource={logList}
            size='middle'
            rowSelection={rowSelection}
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            loading={loading}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageNum,
              total: totalCount,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
      </div>
    );
  }
}

export default InterfaceLog;
